<template>
    <div class="home-container">
      <div class="header">
        <h1>热门电影推荐</h1>
        <p>探索精彩电影世界</p>
      </div>
      
      <div class="filters">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索电影..." 
          class="search-input"
        >
        <div class="filter-buttons">
          <button 
            v-for="genre in genres" 
            :key="genre" 
            :class="['genre-btn', { active: activeGenre === genre }]"
            @click="toggleGenre(genre)"
          >
            {{ genre }}
          </button>
        </div>
      </div>
      
      <div v-if="loading" class="loading-container">
        <Spinner size="large" />
      </div>
      
      <div v-else>
        <div v-if="filteredMovies.length === 0" class="no-results">
          <p>没有找到匹配的电影</p>
        </div>
        
        <div v-else class="movies-grid">
          <MovieCard 
            v-for="movie in filteredMovies" 
            :key="movie.id" 
            :movie="movie" 
            @click="viewMovie(movie.id)"
          />
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { getAllMovies } from '../api'
  import MovieCard from '../components/MovieCard.vue'
  import Spinner from '../components/Spinner.vue'

  const router = useRouter()
  const movies = ref<any[]>([])
  const loading = ref(true)
  const searchQuery = ref('')
  const activeGenre = ref('全部')
  const errorMessage = ref('')

  // 定义电影接口
  interface Movie {
    id?: number
    title: string
    director: string
    year: number
    description: string
    userId: number
    actors: string // 新增演员字段
    cover: string // 新增封面图字段
    playUrl: string // 新增播放链接字段
  }

  const genres = ['全部', '动作', '喜剧', '科幻', '爱情', '恐怖', '剧情']

  // 获取电影数据
  onMounted(async () => {
    try {
      const response = await getAllMovies()
      if (response.data.success) {
        // 数据映射：将后端字段转换为前端组件所需字段
        const mappedMovies = response.data.data.map((movie: any) => ({
          id: movie.id,
          title: movie.title || '无标题',
          director: movie.authorName || '未知导演',
          year: movie.addedTime ? new Date(movie.addedTime).getFullYear() : new Date().getFullYear(),
          description: movie.desc || '暂无简介',
          userId: movie.userid || 0,
          actors: movie.actors || '', // 新增演员字段
          cover: movie.picPaths || '', // 新增封面图字段
          playUrl: movie.playUrl || '' // 新增播放链接字段
        }))
        movies.value = mappedMovies
        console.log('获取到的电影列表:', mappedMovies)
      } else {
        errorMessage.value = '获取电影数据失败'
      }
    } catch (error) {
      errorMessage.value = '获取电影数据失败，请稍后再试'
      console.error('获取电影列表失败:', error)
    } finally {
      loading.value = false
    }
  })

  // 过滤电影列表
  const filteredMovies = computed(() => {
    let result = movies.value

    // 根据搜索框内容过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      result = result.filter(movie => 
        movie.title.toLowerCase().includes(query) || 
        movie.description.toLowerCase().includes(query)
      )
    }

    // 根据选择的类型过滤
    if (activeGenre.value !== '全部') {
      result = result.filter(movie => movie.genres?.includes(activeGenre.value))
    }

    return result
  })

  // 切换电影类型
  const toggleGenre = (genre: string) => {
    activeGenre.value = activeGenre.value === genre ? '全部' : genre
  }

  // 查看电影详情
  const viewMovie = (id: number) => {
    router.push({ name: 'movie-detail', params: { id } })
  }
</script>
  
  <style scoped lang="scss">
  .home-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .header {
    text-align: center;
    margin-bottom: 40px;
    
    h1 {
      font-size: 36px;
      color: #2c3e50;
      margin-bottom: 10px;
    }
    
    p {
      font-size: 18px;
      color: #7f8c8d;
    }
  }
  
  .filters {
    margin-bottom: 30px;
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  }
  
  .search-input {
    width: 100%;
    padding: 14px 20px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    font-size: 16px;
    margin-bottom: 20px;
    transition: all 0.3s;
    
    &:focus {
      border-color: #3498db;
      outline: none;
      box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
    }
  }
  
  .filter-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .genre-btn {
    padding: 10px 20px;
    border: none;
    border-radius: 30px;
    background: #f5f5f5;
    color: #555;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      background: #e0e0e0;
    }
    
    &.active {
      background: linear-gradient(to right, #3498db, #2c3e50);
      color: white;
    }
  }
  
  .movies-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 25px;
    margin-top: 20px;
  }
  
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
  
  .no-results {
    text-align: center;
    padding: 50px 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    
    p {
      font-size: 18px;
      color: #7f8c8d;
    }
  }
  
  @media (max-width: 768px) {
    .movies-grid {
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
    }
  }
  
  @media (max-width: 576px) {
    .header {
      h1 {
        font-size: 28px;
      }
      
      p {
        font-size: 16px;
      }
    }
    
    .movies-grid {
      grid-template-columns: 1fr;
    }
  }
  </style>